const express = require('express')
const mysql = require('mysql')
const db = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: '123456789',
  database: 'learner'
})

module.exports = function () {
  let router = express.Router()

  router.get('/', (req, res) => {
    db.query(`SELECT * FROM msg_table`, (err, msglist) => {
      if (err) {
        console.error(err)
        res.status(500).send('database error').end()
      } else {
        res.render('admin/message.ejs', { msglist })
      }
    })
  })

  router.post('/', (req, res) => {
    let name = req.body.name
    let email = req.body.email
    let phone = req.body.phone
    let subject = req.body.subject
    db.query(`INSERT INTO msg_table (name, email, phone, subject) VALUE ('${name}', '${email}', '${phone}', '${subject}')`, (err, data) => {
      if (err) {
        console.log(err)
        res.status(500).send('database error').end()
      } else {
        res.redirect('/admin/msg')
      }
    })
  })

  return router
}
